import wx
import MySQLdb as sql
import _mysql_exceptions as sqlExceptions

class ChatFrame(wx.Frame):
    
    def __init__(self):
        
        
#        wx.Frame(wx.Window parent, int id=-1, string title='', wx.Point pos = wx.DefaultPosition, wx.Size size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, string name = "frame")
        # try
        self.db = sql.connect("127.0.0.1","root","toor","toyota")
        self.db.autocommit(True)
        self.cur = self.db.cursor()
        
        wx.Frame.__init__(self, parent=None, title="North Tampa Toyota",size=(1024,768))

        sizer = wx.BoxSizer(wx.VERTICAL)
        innerSizer = wx.BoxSizer(wx.HORIZONTAL)
        innerSizerChoice1 = wx.BoxSizer(wx.HORIZONTAL)
        innerSizerChoice2 = wx.BoxSizer(wx.HORIZONTAL)
        innerSizerChoice3 = wx.BoxSizer(wx.HORIZONTAL)
        
        self.text = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.ctrl = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER, size=(300, 25))
        self.send = wx.Button(self,-1,"Send")
        self.sendChoices = wx.Button(self,-1,"Send ChoiceBoxes")
        
        self.modelChoices = {}
        
        self.modelChoices['name'] = wx.Choice(self,name="name")
        self.modelChoices['year'] = wx.Choice(self,name="year")
        self.modelChoices['cylinders'] = wx.Choice(self,name="cylinders")
        self.modelChoices['horse_power'] = wx.Choice(self,name="horse_power")
        self.modelChoices['torque'] = wx.Choice(self,name="torque")
        self.modelChoices['automatic'] = wx.Choice(self,name="automatic")
        self.modelChoices['inline'] = wx.Choice(self,name="inline")    
        self.UpdateChoices(self.modelChoices)
        
        for key,value in self.modelChoices.iteritems():
                innerSizerChoice1.Add(value)
        
        sizer.Add(innerSizerChoice1,5,wx.EXPAND)
        sizer.Add(innerSizerChoice2,5,wx.EXPAND)
        sizer.Add(innerSizerChoice3,5,wx.EXPAND)
                
        sizer.Add(self.text, 5, wx.EXPAND)
        sizer.Add(self.ctrl, 0, wx.EXPAND)
        
        
        innerSizer.Add(self.send,5, wx.EXPAND, 10)
        innerSizer.Add(self.sendChoices,5, wx.EXPAND, 10)
        sizer.Add(innerSizer,0,wx.EXPAND)
        
        
        self.SetSizer(sizer)
        
        self.text.Bind(wx.EVT_TEXT,self.OnTextUpdate)
        self.send.Bind(wx.EVT_BUTTON, self.onSend)
        self.sendChoices.Bind(wx.EVT_BUTTON, self.onSendChoices)
        
        self.ctrl.SetFocus()
        
    def OnTextUpdate(self,evt):
        pos = self.text.GetLastPosition()
        self.text.ShowPosition(pos)
        
    def UpdateChoices(self,choiceBoxes):
        for field in choiceBoxes.keys():
            self.cur.execute("SELECT DISTINCT " + field + " FROM model ORDER BY " + field + ";")
            rows = self.cur.fetchall()
            
            choiceBoxes[field].Clear()
            
            choiceBoxes[field].Append('')
            
            for row in rows:
                for item in row:
                    choiceBoxes[field].Append(str(item))
    
    def UpdateResults(self):
        queryResult = self.cur.fetchall()
        val = str()
        for row in queryResult:
                for item in row:
                    val += str(item) + ","
                val = val.strip(",")
                val += "\n"
        self.text.SetValue(val) 
        
    def compose(self,array):
        tmp = "SELECT * FROM model WHERE "
        splitArray = array.split()
        for item in splitArray:
            tmp2 = item.split('=')
            tmp += tmp2[0] + "='" + tmp2[1] + "'" + " AND "
        tmp = tmp.rstrip(" AND ")
        return tmp
    
    def composeChoices(self):
        query = "SELECT * FROM model WHERE "
        for value in self.modelChoices.itervalues():
            if value.GetStringSelection():
                query += value.GetName() + "=" + repr(str(value.GetStringSelection())) + " AND "
        query = query.rstrip("AND ")
        return query

    def SQLError(self,err):
        print type(err)
        if isinstance(err,sqlExceptions.ProgrammingError):
            dlg = wx.MessageDialog(self, err[1], "Error", wx.OK | wx.ICON_HAND)
            dlg.ShowModal()
            dlg.Destroy()
        elif isinstance(err,IndexError):
            dlg = wx.MessageDialog(self, "Empty query error.", "Error", wx.OK | wx.ICON_HAND)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            print err.message
            
    def onSendChoices(self,evt):
        try:
            composed = self.composeChoices()
            print composed
        
            self.cur.execute(composed)
            self.ctrl.SetValue("")
            self.UpdateResults()
        except Exception, err:
            print err
            self.SQLError(err)   
   
    def onSend(self,evt):
        try:
            composed = self.compose(str(self.ctrl.GetValue()))
            print composed
            
            self.cur.execute(composed)
            self.ctrl.SetValue("")
            
            # print rows
            self.UpdateResults()
        
        except Exception, err:
            print err
            self.SQLError(err)
       
if __name__ == '__main__':
    app = wx.App(False)
    frame = ChatFrame()
    frame.Centre()
    frame.Show()
    app.MainLoop()


#    def composeFrom(self,qItems):
#        temp = " FROM "
#        for item in qItems:
#            temp += item + ","
#        temp = temp.rstrip("AND ")
#        return temp
#            
#    def composeWhere(self,qItems):
#        temp = " WHERE "
#        for item in qItems:
#            temp += item + " AND "
#        temp = temp.rstrip(" AND ")
#        return temp

#        innerSizerChoice1.Add(self.choiceModelName)
#        innerSizerChoice1.Add(self.choiceModelYear)
#        innerSizerChoice1.Add(self.choiceModelCylinders)
#        innerSizerChoice2.Add( self.choiceModelHorse_Power)
#        innerSizerChoice2.Add( self.choiceModelTorque)
#        innerSizerChoice2.Add(self.choiceModelAutomatic)
#        innerSizerChoice3.Add(self.choiceModelInline)
